package com.gdut.simple.view.activity.explore;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.gdut.simple.R;
import com.gdut.simple.common.ToastUtils;
import com.gdut.simple.contract.SquareContract;
import com.gdut.simple.data.entity.Post;
import com.gdut.simple.event.RxBus;
import com.gdut.simple.event.SquareEvent;
import com.gdut.simple.presenter.SquarePresenter;
import com.gdut.simple.view.activity.user.LoginActivity;
import com.gdut.simple.view.adapter.PostAdapter;
import com.gdut.simple.view.adapter.base.AbsRecyclerAdapter;
import com.gdut.simple.view.basic.AbsBasicActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;


public class SquareActivity extends AbsBasicActivity implements SquareContract.View {

    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_item_list_view)
    RecyclerView mItemListView;
    @BindView(R.id.id_swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    private PostAdapter mPostAdapter;
    private List<Post> mPostList;

    private SquareContract.Presenter mSquarePresenter;
    private int mCurrentPage = 1;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_square);
        ButterKnife.bind(this);
        new SquarePresenter(this);
        initToolbar();
        initRefreshLayout();
        initRecyclerView();
        RxBus.getDefault().toObservable(SquareEvent.class).subscribe(new Action1<SquareEvent>() {
            @Override
            public void call(SquareEvent squareEvent) {
                mSquarePresenter.refresh();
            }
        });
    }

    private void initToolbar() {
        mToolbar.setTitle(R.string.nav_square);
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }

    private void initRefreshLayout() {
        mSwipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(this, R.color.colorPrimaryDark),
                ContextCompat.getColor(this, R.color.colorPrimary),
                ContextCompat.getColor(this, R.color.colorPrimaryDark));
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mSquarePresenter.refresh();
                mCurrentPage = 1;
            }
        });
    }

    private void initRecyclerView() {
        mItemListView.setLayoutManager(new LinearLayoutManager(this));
        mItemListView.setItemAnimator(new DefaultItemAnimator());
        mPostList = new ArrayList<>();
        mPostAdapter = new PostAdapter(this, mPostList);
        mItemListView.setAdapter(mPostAdapter);
        mPostAdapter.setOnItemClickListener(new AbsRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                Intent intent = new Intent(SquareActivity.this, PostDetailActivity.class);
                if (mPostList.get(position) != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mPostList.get(position).getObjectId());
                    bundle.putParcelable("post", mPostList.get(position));
                    bundle.putString("time", mPostList.get(position).getCreatedAt());
                    if (mPostList.get(position).getAuthor().getProfile() != null) {
                        bundle.putString("profile", mPostList.get(position).getAuthor().getProfile().getUrl());
                    } else {
                        bundle.putString("profile", "");
                    }
                    bundle.putString("name", mPostList.get(position).getAuthor().getNickName());
                    intent.putExtras(bundle);
                }
                startActivity(intent);
            }

            @Override
            public boolean onLongClick(View view, int position) {
                return false;
            }
        });
        mItemListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
                int totalItemCount = recyclerView.getLayoutManager().getItemCount();
                if (lastVisibleItem >= totalItemCount - 1 && dy > 0) {
                    mSquarePresenter.loadMore(++mCurrentPage);
                }
            }
        });
    }

    @Override
    protected void loadData() {
        mSquarePresenter.refresh();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_square, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add_post:
                if (!isLogin()) {
                    Snackbar.make(mItemListView, "未登录", Snackbar.LENGTH_LONG)
                            .setAction("登陆", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    startActivity(new Intent(SquareActivity.this, LoginActivity.class));
                                }
                            }).show();
                    return false;
                }
                startActivity(new Intent(SquareActivity.this, PublishActivity.class));
                break;
        }
        return true;
    }

    @Override
    public List<Post> getItemList() {
        return mPostList;
    }

    @Override
    public void refreshList() {
        if (mPostAdapter != null) {
            mPostAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showRefreshProgress() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    }

    @Override
    public void hideRefreshProgress() {
        if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void setPresenter(@NonNull SquareContract.Presenter presenter) {
        this.mSquarePresenter = presenter;
    }
}
